package com.sams.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.Notice;
import com.sams.entity.NoticeShowinfo;
import com.sams.entity.School;
import com.sams.entity.User;
import com.sams.service.NoticeService;
import com.sams.util.PropertiesUtil;
import com.sams.util.ZipFileUtil;

@RequestMapping("/notice")
@Controller
public class NoticeController {
	
	@Autowired
	private NoticeService service;
	@RequestMapping("/list")
	public String listSchool(Integer currentPage,String name,Model model) {
		if(currentPage==null) {
			currentPage=1;
		}
		// 以前存 list  和  page对象 ，现在存 分页框架的pageInfo
		// PageInfo 相当于  以前的Page 
		 
		PageInfo<Notice> pageInfo = service.list(currentPage,name);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("name", name);
		return "notice";
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public List<Notice> getList(){
		List<Notice> list = service.getList();
		System.out.println(list);
		return list;
	}
	
	
	@RequestMapping("/listFront")
	public String listFront(Integer currentPage,String name,Model model) {
		if(currentPage==null) {
			currentPage=1;
		}
		// 以前存 list  和  page对象 ，现在存 分页框架的pageInfo
		// PageInfo 相当于  以前的Page 
		 
		PageInfo<Notice> pageInfo = service.list(currentPage,name);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("name", name);
		return "detailnoticeList";
	}
	
	/**
	 * 添加
	 * @param file
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/add")
	public String add(
			@RequestParam("name") String name,
			@RequestParam("content") String content,
			@RequestParam("filepath") MultipartFile filepath,
			HttpServletRequest request,Model model) throws IllegalStateException, IOException {
		// 1.获取前端表单上传的文件，获取文件名getOriginalFilename()，判断是否是Excel文件
		/*String fileName = filepath.getOriginalFilename();
		System.out.println(fileName);*/
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		File newFile=null;
		try {
 

			File file = new File(PropertiesUtil.getProperty("imagePath") + File.separator + "notice");
			if (!file.exists()) {// 如果文件夹不存在
				file.mkdirs();// 创建文件夹
			}
			String noticefile = getFileName(filepath.getOriginalFilename());
			newFile = new File(file.getPath() + File.separator + noticefile);
			// 上传文件
			filepath.transferTo(newFile);

			// 添加notice
			Notice notice = new Notice();
			notice.setName(name);
			notice.setContent(content);
			notice.setFilepath("notice/" + noticefile);
			notice.setCreatedate(new Date());
			int count = service.add(notice);

			return "redirect:list";
		} catch (IOException e) {
			 //删除文件 
			if(newFile!=null) {
				newFile.delete();
			}
			e.printStackTrace();
			return "error";
		}
	}
	
	@RequestMapping("/delete")
	public String delete(Integer id) {
		Notice notice = service.findById(id);
		//先删除服务器上的文件 ，再删除业务数据   同时还删除浏览人的记录
		File file = new File(PropertiesUtil.getProperty("imagePath") + File.separator + notice.getFilepath());
		if(file!=null) {
			file.delete();
		}
		//删除
		service.delete(id);

		return "forward:/notice/list";
	}
	//新文件名字
	public String getFileName(String fileName) {
		String filePrefix=fileName.substring(0,fileName.lastIndexOf('.'));
        String fileSuffix=fileName.substring(fileName.lastIndexOf('.'), fileName.length());
       return filePrefix+(int)(Math.random()*9000+1000)+fileSuffix;
	}
	@RequestMapping("/downFile")
	public String downFile(Integer id, HttpServletRequest request, HttpServletResponse response) {
		//根据id 查询地址
		Notice notice = service.findById(id);
		  File file = new File(PropertiesUtil.getProperty("imagePath") + File.separator + notice.getFilepath());
		  ZipFileUtil.downloadFile(file, response, false);
		  return null;
	}
	@RequestMapping("/detailnotice")
	public String detailnotice(Integer type,Integer id, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		//根据id 查询地址
		Notice notice = service.findById(id);
		// 来自首页的查看 ， 需要记录当前点击人
		if(type!=null) {
			User user =  (User)request.getSession().getAttribute("user");
			if(user==null) {
				model.addAttribute("error", "会话过期，请重新登录");
				return "error";
			}
			service.addNoticeShow(id, user);
			
			//查询当前详情被哪些用户已阅 （不同级别只看它对应级别的已阅 ，管理员和县看镇id ，）
			// 镇账号 看所有学校用户
			List<NoticeShowinfo> userList=service.listShowUser(id, user);
			 request.setAttribute("userList", userList);
 		}
		
		
		 request.setAttribute("notice", notice);
		  return "detailnotice";
	}
	@ResponseBody
	@RequestMapping("selectSchoolNameByXZId")
	public List<NoticeShowinfo> selectSchoolNameByXZId(Integer noticeId,Integer userId){
		
		List<NoticeShowinfo> list = service.selectSchoolNameByXZId(noticeId,userId);
		return list;
	}
}
